package com.zscat.mallplus.active.controller;


import java.util.Map;
import java.util.Objects;

import javax.annotation.Resource;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zscat.mallplus.component.UserUtils;
import com.zscat.mallplus.util.CommonUtil;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.zscat.mallplus.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zscat.mallplus.active.entity.CmsActive;
import com.zscat.mallplus.active.service.ICmsActiceService;
import com.zscat.mallplus.active.service.ISysStoreService;
import com.zscat.mallplus.annotation.SysLog;
import com.zscat.mallplus.cms.entity.CmsSubject;
import com.zscat.mallplus.cms.service.ICmsSubjectService;
import com.zscat.mallplus.sys.entity.SysStore;
import com.zscat.mallplus.utils.CommonResult;
import com.zscat.mallplus.utils.Maps;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @author mallplus
 * @date 2019-12-17
 * 分销审核
 */
@Slf4j
@RestController
@RequestMapping("/active")
@Validated
public class CmsActiveController {

    @Resource
    private ICmsActiceService iCmsActiceService;
    @Resource
    private ICmsSubjectService iCmsSubjectService;
    @Resource
    private ISysStoreService iSysStoreService;


    @SysLog(MODULE = "活动", REMARK = "后台 活动列表")
    @ApiOperation("后台 活动列表")
    @GetMapping(value = "/mng/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "kw", value = "搜索关键词"),
            @ApiImplicitParam(name = "pageNum", value = "页码"),
            @ApiImplicitParam(name = "pageSize", value = "页大小"),
    })
    public Object mngList(String kw,
                          @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                          @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
            QueryWrapper<CmsActive> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("show_status",true);
            if (Objects.nonNull(kw) && StringUtils.isNotBlank(kw)) {
                kw = "%" + kw.replace(" ", "") + "%";
                queryWrapper.like("active_title", kw)
                        .or().like("active_des", kw);
            }

            queryWrapper.orderByDesc("recommend_status");
            queryWrapper.orderByDesc("gmt_create");
            return new CommonResult().success(iCmsActiceService.page(new Page<CmsActive>(pageNum, pageSize), queryWrapper));
        } catch (Exception e) {
            log.error("后台 活动列表：%s", e.getMessage(), e);
        }
        return new CommonResult().failed();
    }


    @SysLog(MODULE = "活动", REMARK = "查询活动列表")
    @ApiOperation("查询活动列表")
    @GetMapping(value = "/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "activeType", value = "类型  1  精彩活动  2  研学  3  创课"),
            @ApiImplicitParam(name = "popActive", value = "推荐  false  普通  true 推荐  不传 代表所有"),
            @ApiImplicitParam(name = "pageNum", value = "页码"),
            @ApiImplicitParam(name = "pageSize", value = "页大小"),
    })
//    @PreAuthorize("hasAuthority('fenxiao:fenxiaoChecks:read')")
    public Object list(Integer activeType,
                       Boolean popActive,
                       @RequestParam(value = "storeId", defaultValue = "1574")   Long storeId,
                       @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                       @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize
    ) {
        try {
//            LambdaQueryWrapper<CmsActive> wrapper = new QueryWrapper<CmsActive>().lambda().eq(CmsActive::getPopActive, popActive);
            QueryWrapper<CmsActive> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("show_status",true);
            if (Objects.nonNull(popActive)) {
                queryWrapper.eq("pop_active", popActive);
            }
            if (Objects.nonNull(storeId)) {
                queryWrapper.eq("store_id", storeId);
            }
            if (Objects.nonNull(activeType)) {
                queryWrapper.eq("active_type", activeType);
//                wrapper.eq(CmsActive::getActiveType, activeType);
            }
            queryWrapper.orderByDesc("recommend_status");
            queryWrapper.orderByDesc("gmt_create");
            IPage<CmsActive> page = iCmsActiceService.page(new Page<CmsActive>(pageNum, pageSize), queryWrapper);
            page.getRecords().forEach(active -> active.setGmtCreate(active.getGmtCreate()));
            return new CommonResult().success(page);
        } catch (Exception e) {
            log.error("查询活动列表：%s", e.getMessage(), e);
        }
        return new CommonResult().failed();
    }


    @SysLog(MODULE = "活动", REMARK = "查询活动详情")
    @ApiOperation("查询活动详情")
    @GetMapping(value = "/detail/{id:.+}")
    public Object detail(@PathVariable("id") @NotNull Integer id) {
        try {
            CmsActive active = iCmsActiceService.getById(id);
            if (Objects.nonNull(active)) {
                active.setGmtCreate(active.getGmtCreate());
                return new CommonResult().success(active);
            }
        } catch (Exception e) {
            log.error("查询活动详情：%s", e.getMessage(), e);
        }
        return new CommonResult().failed();
    }


    @SysLog(MODULE = "活动", REMARK = "新建或者修改活动")
    @ApiOperation("新建或者修改活动")
    @PostMapping(value = "/saveOrUpdate")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = " 传为修改，不传为新增"),
            @ApiImplicitParam(name = "activeTitle", value = "标题"),
            @ApiImplicitParam(name = "sort", value = "排序，越大靠前"),
            @ApiImplicitParam(name = "activeDes", value = "副标题"),
            @ApiImplicitParam(name = "activeDt", value = "详情"),
            @ApiImplicitParam(name = "activeImg", value = "主图"),
            @ApiImplicitParam(name = "activeType", value = "类型"),
//            @ApiImplicitParam(name = "storeId",value = "科技馆 ID"),
            @ApiImplicitParam(name = "popActive", value = "是否推荐  true 是 false 不是"),
    })
    @PreAuthorize("hasAuthority('cms:CmsTopic:read')")
    public Object saveOrUpdate(
            @RequestParam(value = "id", required = false) Long id,
            @RequestParam(value = "activeTitle") @NotBlank String activeTitle,
            @RequestParam(value = "sort", required = false) Integer sort,
            @RequestParam(value = "activeDes", required = false)  String activeDes,
            @RequestParam(value = "activeDt",required = false)  String activeDt,
            @RequestParam(value = "activeImg",required = false)  String activeImg,
            @RequestParam(value = "activeType") @NotNull Integer activeType,
//            @NotNull Integer storeId,
            @RequestParam(value = "popActive", defaultValue = "false") Boolean popActive,
            @RequestParam(value = "showStatus", defaultValue = "false") Boolean showStatus,
            @RequestParam(value = "refGoodsNumber",required = false) String refGoodsNumber,
            @RequestParam(value = "recommendStatus", defaultValue = "false") Boolean recommendStatus
    ) {

        System.out.println(" - - - - - - >  新建或者修改活动开始");
        if (StringUtils.isNotBlank(refGoodsNumber)) {
            refGoodsNumber = refGoodsNumber.replace("，",",");
        }

        CmsActive active = new CmsActive();
        active.setId(id);
        active.setActiveTitle(activeTitle);
        active.setActiveDes(activeDes);
        active.setActiveDt(activeDt);
        active.setActiveImg(activeImg);
        active.setActiveType(activeType);
        active.setSort(sort);
        active.setShowStatus(showStatus);
        active.setRecommendStatus(recommendStatus);
        active.setRefGoodsNumber(refGoodsNumber);

//        Integer storeId = UserUtils.getCurrentMember().getStoreId();
//        if (Objects.nonNull(storeId)){
//            active.setStoreId(storeId);
//        }
        active.setPopActive(popActive);
        try {
            if (iCmsActiceService.saveOrUpdate(active)) {
                System.out.println(" - - - - - - >  新建或者修改活动成功");
                return new CommonResult().success(active);
            }
        } catch (Exception e) {
            log.error("新建或者修改活动：%s", e.getMessage(), e);
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "活动", REMARK = "删除活动")
    @ApiOperation("删除活动")
    @PostMapping(value = "/del/{id:.+}")
    public Object del(@PathVariable("id") @NotNull @Min(1) Long id) {
        CmsActive active = iCmsActiceService.getById(id);

        try {
            if (Objects.nonNull(active)) {
                if (iCmsActiceService.removeById(active)) {
                    return new CommonResult().success(active);
                }
            }
        } catch (Exception e) {
            log.error("删除活动：%s", e.getMessage(), e);
        }
        return new CommonResult().failed();
    }


    @SysLog(MODULE = "活动", REMARK = "获取研学 创课 活动的介绍文章 ID ")
    @ApiOperation("获取研学  创课 活动的介绍文章 ID ")
    @GetMapping(value = "/getId")
    public Object getId() {

        QueryWrapper<CmsSubject> wrapper = new QueryWrapper<>();
        // 研学
        QueryWrapper<CmsSubject> yx = wrapper.eq("category_id", 51).last("limit 1");
        CmsSubject yxSbj = iCmsSubjectService.getOne(yx);

        QueryWrapper<CmsSubject> wrapper1 = new QueryWrapper<>();
        // 创课
        QueryWrapper<CmsSubject> ck = wrapper1.eq("category_id", 52).last("limit 1");
        CmsSubject ckSbj = iCmsSubjectService.getOne(ck);
        try {
            if (Objects.nonNull(yxSbj) && Objects.nonNull(ckSbj)) {

                SysStore s1 = iSysStoreService.getById(yxSbj.getStoreId());
                yxSbj.setStoreName(s1.getName());

                SysStore s2 = iSysStoreService.getById(ckSbj.getStoreId());
                ckSbj.setStoreName(s2.getName());

                Map<String, CmsSubject> r = Maps.newHashMap();
                r.put("yx", yxSbj);
                r.put("ck", ckSbj);
                return new CommonResult().success(r);
            }
        } catch (Exception e) {
            log.error("获取研学，创课 活动的介绍文章 ID ：%s", e.getMessage(), e);
        }
        return new CommonResult().failed();
    }



}


